import { JXDef } from "../../../conventions/JXCommon";
import { OBJECT_COPY, PRIORITY_VIEW } from "../../../Core/CoreDefine";
import GViewBase from "../../../Core/GView/GViewBase";
import { AudioMgr } from "../../../Core/Manager/AudioMgr";
import { VIEW_ID } from "../../Common/UI";
import { Res } from "../../Common/UIResources";
import { JXLocales } from "../../Common/Zh";
import RJXItem from "../../Data/RunTime/RunRaw/RJXItem";
import GameMgr from "../../Logic/GameMgr";
import JXItem from "../Common/JXItem";
import { GCtrl } from './../../../Core/GCtrl';
import { CMsg, CURRENCY, ITEM_DETAIL_FLAG, ITEM_TYPE, PART_ITEM, PointInfo, REWARD, SQUAD_BUTTON } from './../../Common/Define';

const { ccclass, property, menu, executeInEditMode } = cc._decorator;
@ccclass @menu('View/Tip/RewardCtrl')

export default class RewardCtrl extends GViewBase {
    @property({
        type: cc.Node,
        tooltip: "图标自动排序"
    })
    iconLay: cc.Node = null;

    @property({
        type: cc.Node,
        tooltip: "图标自动排序"
    })
    iconLay1: cc.Node = null;

    @property({
        type: cc.Node,
        tooltip: "终点"
    })
    endPoint: cc.Node = null;

    @property({
        type: cc.Node,
        tooltip: "确定"
    })
    ui_queding: cc.Node = null;
    private _rewardData: number[][] = null;
    private _startPoint: cc.Node;
    private _index = 0;
    private _bool = false
    private _featurtArr = [];
    private _reward: Function = null;
    private _featurtNum: number = 0;
    private _featurtType: number = REWARD.ALL;
    onGLoad() {
        this.node.setContentSize(cc.winSize);
        GCtrl.ES.on(CMsg.client.home.onFeature, this, this.onFeature.bind(this), PRIORITY_VIEW);

    }

    onFeature(_, FEAT: FEAT) {
        // console.log('FEAT', FEAT);
        if (FEAT.reward.length > 0 && FEAT.bool) {
            this._rewardData.forEach((s, count) => {
                if (s[1] == FEAT.reward[1] && s[0] == FEAT.reward[0] && count == FEAT.index) {
                    // console.log("s[2]", s[2], FEAT.reward[2]);
                    s[2] += FEAT.reward[2];
                    // console.log("s[2]++", s[2]);
                }
            })
        }

        let bool = false;
        this._featurtArr.forEach((v, count) => {
            if (bool) {
                return
            }
            if (this._featurtNum == this._featurtArr.length) {
                bool = true;
                this._reward();
            }
            if (count == this._featurtNum) {
                bool = true;
                this._featurtNum++;
                GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.featureCtrl, v);
            }
        })
    }

    onGStart(data: number[][], type?: number) {
        if (type) {
            console.log("更换特写展示类型");
            this._featurtType = type;
        }
        this._rewardData = OBJECT_COPY(data);
        // console.log('onGStart', this._rewardData);
        GCtrl.ES.emit(CMsg.client.bag.onBagItemChange, this._rewardData);
        let allHero = GameMgr.rHeroData.getHaveHeros(SQUAD_BUTTON.ALL);
        this._rewardData.forEach((v, count) => {
            v.forEach((value, index) => {
                let FEATREWARD: FEATREWARD = {
                    index: count,
                    reward: v
                }

                if (this._featurtType == REWARD.ALL) {
                    if (index == PART_ITEM.TYPE && (value == ITEM_TYPE.HERO || value == ITEM_TYPE.PROP)) {
                        if (v[PART_ITEM.ID] >= 1001 && v[PART_ITEM.ID] <= (1000 + allHero.have.length + allHero.notHave.length)) {
                            this._featurtArr.push(FEATREWARD);
                        }
                    }
                } else if (this._featurtType == REWARD.HERO) {
                    if (index == PART_ITEM.TYPE && (value == ITEM_TYPE.HERO)) {
                        if (v[PART_ITEM.ID] >= 1001 && v[PART_ITEM.ID] <= (1000 + allHero.have.length + allHero.notHave.length)) {
                            this._featurtArr.push(FEATREWARD);
                        }
                    }
                }
            })
        })


        this._reward = () => {
            // console.log('this._rewardData', this._rewardData);
            // GCtrl.ES.emit(CMsg.client.bag.onBagItemChange, this._rewardData);
            this.node.getChildByName('bg').active = true;
            this.creatorReward();
            AudioMgr.Ins().playEffect(Res.audio.reward)
            this.win.maskNode.opacity = 200;
        }

        if (this._featurtArr.length > 0) {
            this.node.getChildByName('bg').active = false;
            let bool = false;
            this._featurtArr.forEach((v) => {
                if (bool) {
                    return;
                }
                bool = true;
                this._featurtNum++;
                // console.log("this._featurtNum", this._featurtNum);
                GameMgr.jumpToMgr.jumpGoTo(VIEW_ID.featureCtrl, v);
            })
        } else {
            this._reward();
        }
    }

    /**双倍领取*/
    public adVideo() {
        this.ui_queding.active = false;
        GameMgr.sdkMgr.watchAd(() => {
            GameMgr.sdkMgr.umaSetPoint(JXDef.umaPoint.rewardCtrl, { msg: PointInfo.rewardCtrl_ad })
            this.ui_queding.active = true;
            GCtrl.ES.emit(CMsg.client.bag.onBagItemChange, this._rewardData);
            GameMgr.uiMgr.showToast(JXLocales.tip.alldoubleClick);

            this.close();
        }, () => {
            this.ui_queding.active = true;
        })
    }

    close() {
        this._rewardData = [];
        this._featurtArr = [];
        this.onClose();
    }

    protected change(CURRENCYANIM: CURRENCYANIM) {
        var coin = null;
        var worldPos = null;
        var ccPos = null;
        if (CURRENCYANIM.id == CURRENCY.GOLD) {
            if (GameMgr.uiMgr.uiRoot.getChildByName('TopUiItem')) {
                coin = GameMgr.uiMgr.uiRoot.getChildByName('TopUiItem').getChildByName('coinBg').getChildByName('coin');
                worldPos = coin.parent.convertToWorldSpaceAR(coin.position);
                ccPos = this.node.convertToNodeSpaceAR(worldPos);
            }
        }
        if (CURRENCYANIM.id == CURRENCY.YUSHI) {
            if (GameMgr.uiMgr.uiRoot.getChildByName('TopUiItem')) {
                coin = GameMgr.uiMgr.uiRoot.getChildByName('TopUiItem').getChildByName('gemBg').getChildByName('gem');
                worldPos = coin.parent.convertToWorldSpaceAR(coin.position);
                ccPos = this.node.convertToNodeSpaceAR(worldPos);
            }

        }

        if (ccPos) {
            this.playAnimation(new cc.Vec2(0, 0), ccPos, () => {
                this.ui_queding.active = true;
            }, CURRENCYANIM);
        } else {
            this.ui_queding.active = true;
        }
    }

    /**创建页面 */
    protected creatorReward() {
        let bool = false;
        this.assetImpl.prefab(Res.prefab.item.jxItem, (prefab) => {
            this._rewardData.forEach((value, index) => {
                let comp = this.assetImpl.addGChild<JXItem>(prefab);
                if (this._rewardData.length > 5) {
                    comp.node.parent = this.iconLay1;
                } else {
                    comp.node.parent = this.iconLay;
                }

                let item = new RJXItem(value);
                comp.setView(item, ITEM_DETAIL_FLAG.BAG | ITEM_DETAIL_FLAG.NUMPOS_ITEM_BC | ITEM_DETAIL_FLAG.NOT_TOUCH | ITEM_DETAIL_FLAG.SHOWLIGHT | ITEM_DETAIL_FLAG.LIGHT);
                if (item.id == CURRENCY.GOLD || item.id == CURRENCY.YUSHI) {
                    bool = true;
                    this.scheduleOnce(() => {
                        let CURRENCYANIM: CURRENCYANIM = {
                            startPos: comp.node.position,
                            id: item.id
                        }
                        this.change(CURRENCYANIM);
                    }, 0.2)
                }
            });
        })
        if (!bool) {
            this.ui_queding.active = true;
        }
    }



    /**
* 已知两点求距离
* @param {cc.Vec2} pos1
* @param {cc.Vec2} pos2
*/
    public calcDistance(pos1: cc.Vec2, pos2: cc.Vec2) {
        let xdiff = pos1.x - pos2.x;
        let ydiff = pos1.y - pos2.y;
        let dis = Math.pow((xdiff * xdiff + ydiff * ydiff), 0.5);
        return dis;
    };

    /**
     * 播放金币落袋特效
     * @param startPos  生成位置
     * @param _endPoint 
     * @param callback 完成后的回调
     */
    public playAnimation(startPos: cc.Vec2, _endPoint: cc.Vec2, callback: Function, CURRENCYANIM: CURRENCYANIM) {
        AudioMgr.Ins().playEffect(Res.audio.coin);
        let ranCount = 15
        //最终位置
        let endPos = _endPoint;
        this.playCoinFlyAnim(ranCount, startPos, endPos, callback, CURRENCYANIM)
    }

    /**金币落袋具体实现方法 */
    protected playCoinFlyAnim(count: number, startPos: cc.Vec2, endPos: cc.Vec2, callback: Function, CURRENCYANIM: CURRENCYANIM, r: number = 50) {
        //金币分散成圆
        let points = this.getCirclePoints(r, startPos, count);
        let coinNodeList = points.map(pos => {
            var coin = new cc.Node("New Sprite");
            coin.addComponent(cc.Sprite);
            var sprite = coin.getComponent(cc.Sprite);
            if (CURRENCYANIM.id == CURRENCY.GOLD) {
                this.assetImpl.spriteAtlasFrame(sprite, Res.texture.views.icon, 'icon_101');
            }
            if (CURRENCYANIM.id == CURRENCY.YUSHI) {
                this.assetImpl.spriteAtlasFrame(sprite, Res.texture.views.icon, 'icon_100');
            }
            // cc.find('Canvas').addChild(coin);
            this.node.addChild(coin);
            coin.setPosition(startPos.x, startPos.y);
            return {
                node: coin,
                startPos: startPos,
                midPos: pos,
                endPos: endPos,
                dis: this.calcDistance(pos, endPos)
            }
        })

        //执行动作
        let i = 0;
        coinNodeList.forEach((item, idx) => {
            i++;
            cc.tween(item.node)
                .to(0.35, { position: cc.v2(item.midPos.x, item.midPos.y) })//初始位置
                .delay(idx * 0.01)
                .to(0.35, { position: cc.v2(item.endPos.x, item.endPos.y) })//终点
                .call(() => {
                    item.node.destroy();
                })
                .union()
                .start()
        });
        this.scheduleOnce(() => {
            callback();
        }, 0.2)
    }
    /**
   * 以某点为圆心，生成圆周上等分点的坐标
   *
   * @param {number} r 半径
   * @param {cc.Vec2} pos 圆心坐标
   * @param {number} count 等分点数量
   * @param {number} [randomScope=80] 等分点的随机波动范围
   * @returns {cc.Vec2[]} 返回等分点坐标
   */
    protected getCirclePoints(r: number, pos: cc.Vec2, count: number, randomScope: number = 50): cc.Vec2[] {
        let points = []
        for (let i = 0; i < count; i++) {
            let radians = (Math.PI / 180) * Math.round(360 / count)
            let x = pos.x + r * Math.sin(radians * i)
            let y = pos.y + r * Math.cos(radians * i)
            points.unshift(cc.v3(x + Math.random() * randomScope, y + Math.random() * randomScope, 0))
        }
        return points
    }

    update() {
        this._index++;
        if (this._bool) {
            return;
        }
        if (this._index == 100) {
            this._bool = true;

        }
    }
}   